package com.shushan.invitecode;

import android.app.Dialog;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.net.bean.NetRetBean;
import com.android.net.core.common.RequestType;
import com.android.net.helper.NetHelper;
import com.android.net.listener.common.CallbackCode;
import com.android.net.url.UrlParse;
import com.shushan.base.NavigationLoseActivity;
import com.shushan.invitecode.bean.DayBean;
import com.shushan.invitecode.bean.InviteBean;
import com.shushan.invitecode.bean.PatchBean;
import com.shushan.network.UrlCommParse;
import com.shushan.network.UrlConst;
import com.shushan.network.listener.NetSingleCommListener;
import com.shushan.network.listener.NetStrCommListener;
import com.shushan.pages.InviteActivity;
import com.shushan.pages.OpenVipSpendActivity;
import com.shushan.shushanbao.BabyApplication;
import com.shushan.shushanbao.R;
import com.shushan.util.DateUtils;
import com.shushan.util.DensityUtil;
import com.shushan.util.Session;
import com.shushan.util.SolarYear;
import com.shushan.util.StringTools;
import com.shushan.util.TMUitil;
import com.shushan.util.UmengEventUtil;


import java.text.ParseException;
import java.util.Calendar;
import java.util.List;

import static android.widget.LinearLayout.HORIZONTAL;
import static android.widget.LinearLayout.VERTICAL;

/**
 * @ClassName: InviteCalendarActivity
 * @Desciption: 赠送好友课程万年历
 * @author: yichaohua
 * @date: 2018-09-14
 */
public class InviteCalendarActivity extends NavigationLoseActivity implements View.OnClickListener{

    private static final String TAG = "InviteCalendarActivity";

    private LinearLayout calendarLayout;
    private TextView monthTextView;
    private TextView ruleTextView;
    private TextView totalText;
    private TextView patchText;
    private TextView taskText;
    private ImageView taskImg;
    private ImageView leftImg,rightImg;
    private Button btnMyInviteCode;
    private Dialog activeRuleDialog;
    private Dialog inviteDialog;
    private Dialog patchDialog;
    private Dialog patchSuccessDialog;
    private Button btnCheckIn;

    private final String[] weekday ={"日","一","二","三","四","五","六"};
    private int firstWeekDay;//每月的第一天是周几
    private int sumOfSolarMonth;//每一月的天数
    int currentDay = 0;//系统的day
    int currentYear = 0;
    int currentMonth = 0;
    int nowMonth;
    int nowYear;
    int m;//控制系统当天的背景颜色
    private InviteBean gInviteBean;

    private BabyApplication shuShanApplication = BabyApplication.getInstance();

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.invite_calendar_activity);

        setTitle("签到领取1000元");

        setRightTitle("我的补签卡");

        initViwe();

        initCalendar();

        getInvite(true,"","");

        UmengEventUtil.onEvent(shuShanApplication,"invite_calendar_page_id");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if(activeRuleDialog != null){
            activeRuleDialog.dismiss();
        }

        if(inviteDialog != null){
            inviteDialog.dismiss();
        }

        if(patchDialog != null){
            patchDialog.dismiss();
        }

        if(patchSuccessDialog != null){
            patchSuccessDialog.dismiss();
        }
    }

    private void initViwe() {
        totalText = findViewById(R.id.invite_calendar_total_day_tv);
        patchText = findViewById(R.id.invite_calendar_patch_day_tv);
        calendarLayout = findViewById(R.id.invite_calendar_layout);
        btnMyInviteCode = findViewById(R.id.btn_my_invite_code);
        btnMyInviteCode.setOnClickListener(this);
        monthTextView = findViewById(R.id.invite_calendar_month_tv);
        leftImg = findViewById(R.id.invite_calendar_month_left_img);
        leftImg.setOnClickListener(this);
        rightImg = findViewById(R.id.invite_calendar_month_right_img);
        rightImg.setOnClickListener(this);
        ruleTextView = findViewById(R.id.invite_calendar_tv);
        ruleTextView.setOnClickListener(this);
        taskText = findViewById(R.id.invite_calendar_task_tv);
        taskImg = findViewById(R.id.invite_calendar_task_img);
        btnCheckIn = findViewById(R.id.btn_check_in);
        btnCheckIn.setOnClickListener(this);
    }

    private void initCalendar() {
        monthTextView.setText(DateUtils.getNowDate("yyyy.MM"));
        calendarLayout.removeAllViewsInLayout();
        String currentTime = DateUtils.getNowDate("yyyy年MM月dd日");
        int year = Integer.parseInt(currentTime.substring(0, 4));
        int month = Integer.parseInt(currentTime.substring(5, 7));
        int day = Integer.parseInt(currentTime.substring(8, 10));

        nowYear = year;
        nowMonth = month;
        currentDay = day;
        currentMonth = month;
        currentYear = year;

        SolarYear solar =new SolarYear();//控制阳历的类
        firstWeekDay = solar.getSolarDayDate(year, month);//返回每月第一天是星期几
        sumOfSolarMonth = solar.daysOfMonth(year, month-1);

        calendarLayout.addView(getLayout());
    }

    @Override
    protected void onRightForward() {
        super.onRightForward();
        if(gInviteBean == null){
            showToast("补签卡信息为空");
            return;
        }
        Session.getSession().put("gInviteBean",gInviteBean);

        startActivity(MyRetroactiveCardActivity.class);
    }

    /**
     *
     * @return 整个日期的布局
     */
    public LinearLayout getLayout(){
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        LinearLayout layout = new LinearLayout(this);
        layout.setOrientation(VERTICAL);
        layout.setLayoutParams(params);
        layout.setBackgroundResource(R.drawable.invite_white_shape);

        LinearLayout layout1 = new LinearLayout(this);
        layout1.setOrientation(HORIZONTAL);
        layout1.setLayoutParams(params);
        layout1.setBackgroundColor(Color.parseColor("#E3FEFF"));
        layout1.setPadding(0,18,0,18);
//    	控制周一到周日的标题
        for(int i=0;i<7;i++){
            TextView tv = new TextView(this);
            tv.setTextSize(TypedValue.COMPLEX_UNIT_SP,12);
            tv.setTextColor(getResources().getColor(R.color.btn_blue));
            tv.setGravity(Gravity.CENTER);
            tv.setWidth(getWindowManager().getDefaultDisplay().getWidth()/7);
            tv.setText(weekday[i]);
            layout1.addView(tv);
        }
        layout.addView(layout1);
//    	控制具体实现
        for(int j=1;j<=6;j++){
            layout.addView(getLayout1(j,firstWeekDay,sumOfSolarMonth));
        }
        return layout;
    }

    /**
     *
     * @param j 日期的列数
     * @param k 每月第一天是星期几
     * @param sum 这个月的天数
     * @return 返回日期每一列的布局
     */
    public LinearLayout getLayout1(int j,int k,int sum){
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        LinearLayout layout1 = new LinearLayout(this);
        layout1.setId(300+j);
        layout1.setOrientation(HORIZONTAL);
        layout1.setLayoutParams(params);

        for(int i=1;i<=7;i++){
            LinearLayout.LayoutParams params1 = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT, DensityUtil.dip2px(this,60));
            LinearLayout layout3 = new LinearLayout(this);
            layout3.setBackgroundResource(R.drawable.invite_white_shape);
            layout3.setOrientation(VERTICAL);
            layout3.setId(200+i+(j-1)*7);
            layout3.setGravity(Gravity.CENTER);
            layout3.setLayoutParams(params1);

            final TextView tv = new TextView(this);
            tv.setTextSize(TypedValue.COMPLEX_UNIT_SP,14);
            tv.setTextColor(Color.BLACK);
            tv.setId(i+(j-1)*7);
            tv.setGravity(Gravity.CENTER);
            tv.setWidth(getWindowManager().getDefaultDisplay().getWidth()/7);

            final TextView tv1 = new TextView(this);
            tv1.setTextColor(Color.BLACK);
            tv1.setTextSize(TypedValue.COMPLEX_UNIT_SP,14);
            tv1.setId(100+i+(j-1)*7);
            tv1.setGravity(Gravity.CENTER);
            tv1.setWidth(getWindowManager().getDefaultDisplay().getWidth()/7);
            tv1.setVisibility(View.GONE);

            if(j == 1){//如果是第一列
                if(i-1>=k){//每月的第一天是星期几
                    tv.setText(((i-k)+(j-1)*7)+"");

                    if(((i-k)+(j-1)*7) == currentDay){//当天日期设置背景颜色
                        m = i+(j-1)*7;
                        layout3.setBackgroundResource(R.drawable.invite_yellow_shape);
                        tv1.setVisibility(View.VISIBLE);
                        tv1.setText("邀请");
                        layout3.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                startActivity(InviteActivity.class);
                            }

                        });
                    }
                }
            }else {//其他列
                if((((i-k)+(j-1)*7))<=sum){
                    tv.setText(((i-k)+(j-1)*7)+"");
                    layout3.setVisibility(View.VISIBLE);

                    if(((i-k)+(j-1)*7) == currentDay){
                        m = i+(j-1)*7;
                        layout3.setBackgroundResource(R.drawable.invite_yellow_shape);
                        tv1.setVisibility(View.VISIBLE);
                        tv1.setText("邀请");
                        layout3.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                startActivity(InviteActivity.class);
                            }

                        });
                    }
                }
            }

            layout3.addView(tv);
            layout3.addView(tv1);
            layout1.addView(layout3);
        }
        return layout1;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_my_invite_code://我的邀请码
                startActivity(MyInviteCodeActivity.class);
                break;
            case R.id.invite_calendar_month_left_img:
                setMonth(-1,currentYear, currentMonth);
                break;
            case R.id.invite_calendar_month_right_img:
                setMonth(1,currentYear, currentMonth);
                break;
            case R.id.invite_calendar_tv:
                showRuleDialog();
                break;
            case R.id.btn_check_in:
                startActivity(InviteActivity.class);
                break;
            default:
                break;
        }
    }

    private void setMonth(int next,int year,int month){
        currentMonth = currentMonth + next;
        if(next > 0){
            if(currentMonth>12){
                currentYear = currentYear+1;
                currentMonth = 1;
            }
            if(currentYear>2050){
                currentYear = 2050;
                currentMonth = 12;
                return;
            }
        }else {
            if(currentMonth<1){
                currentYear = currentYear-1;
                currentMonth = 12;
            }
        }

        setCalendar(currentYear, currentMonth);
        getInvite(false,currentYear + "",currentMonth + "");
    }

    private void setCalendar(int year,int month){
        currentMonth = month;
        currentYear = year;

        SolarYear solar = new SolarYear();//控制阳历的类
        firstWeekDay = solar.getSolarDayDate(year, month);//返回每月第一天是星期几
        sumOfSolarMonth = solar.daysOfMonth(year, month-1);

        String yearMinText = year + ((month<10)?(".0"+month):("."+month));
        monthTextView.setText(yearMinText);

        LinearLayout layout = findViewById(300 + 6);
        if((firstWeekDay + sumOfSolarMonth) > 35){
            layout.setVisibility(View.VISIBLE);
        }else {
            layout.setVisibility(View.GONE);
        }

        for(int i=1;i<=42;i++){
            LinearLayout layout1 = findViewById(200+i);
            TextView tv = findViewById(i);
            TextView tv2 = findViewById(100+i);

            layout1.setBackgroundResource(R.drawable.invite_white_shape);
            layout1.setOnClickListener(null);
            tv.setTextColor(Color.BLACK);
            tv.setText("");
            tv2.setText("");
            tv2.setTextColor(Color.BLACK);
            tv2.setVisibility(View.GONE);

            if(i == m){
                tv.setBackgroundColor(0x00000000);//透明色
                if(currentMonth==nowMonth && currentYear==nowYear){
                    layout1.setBackgroundResource(R.drawable.invite_yellow_shape);
                    tv2.setVisibility(View.VISIBLE);
                    tv2.setText("邀请");

                    layout1.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            startActivity(InviteActivity.class);
                        }

                    });
                }
            }
        }

        int j=1;
        for(int i=1;i<=42;i++){
            TextView tv = findViewById(i);
            if(i-1 >= firstWeekDay){
                if(j<=sumOfSolarMonth){
                    tv.setText(j+"");
                    j++;
                }

            }
        }
    }

    private void showRuleDialog() {
        if(activeRuleDialog == null){
            activeRuleDialog = new Dialog(this,R.style.Dialog_Translucent_Background);
            activeRuleDialog.setContentView(R.layout.active_rule_dialog);
            activeRuleDialog.findViewById(R.id.active_rule_btn).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    activeRuleDialog.dismiss();
                }
            });
        }

        if(!activeRuleDialog.isShowing()){
            activeRuleDialog.show();
        }
    }

    private void showPathSuccessDialog(final InviteBean inviteBean,final int day,PatchBean patchBean) {
        patchSuccessDialog = new Dialog(this,R.style.Dialog_Translucent_Background);
        patchSuccessDialog.setContentView(R.layout.patch_success_dialog);
        TextView textView1 = patchSuccessDialog.findViewById(R.id.patch_success_tv1);
        textView1.setText("使用" + DateUtils.getDate("yyyy-MM-dd",patchBean.create_time,"yyyy年MM月dd日") + "获得的补签卡，");
        TextView textView2 = patchSuccessDialog.findViewById(R.id.patch_success_tv2);
        textView2.setText("已补签" + inviteBean.month + "月" + day + "日的缺卡。");

        patchSuccessDialog.findViewById(R.id.patch_success_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                patchSuccessDialog.dismiss();

                getInvite(false,currentYear + "",currentMonth + "");
            }
        });

        if(!patchSuccessDialog.isShowing()){
            patchSuccessDialog.show();
        }
    }

    private void showPathDialog(final DayBean dayBean,final InviteBean inviteBean) {
        patchDialog = new Dialog(this,R.style.Dialog_Translucent_Background);
        patchDialog.setContentView(R.layout.patch_dialog);
        TextView titleText = patchDialog.findViewById(R.id.invite_title_tv);
        titleText.setText(inviteBean.month + "月" + dayBean.day + "日 未完成");
        TextView textView1 = patchDialog.findViewById(R.id.patch_tv1);
        TextView textView2 = patchDialog.findViewById(R.id.patch_tv2);
        Button pathBtn = patchDialog.findViewById(R.id.patch_btn);
        Button cancelBtn = patchDialog.findViewById(R.id.patch_cancel_btn);
        final PatchBean patchBean = inviteBean.getValidePatch();
        if(patchBean != null){
            textView1.setText("未邀请到好友！需要补签。");
            textView2.setText("您有" + inviteBean.getValidePatchCount() + "场补签卡可用");
            pathBtn.setText("使用补签卡");
            pathBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    patchDialog.dismiss();

                    patchCard(inviteBean,patchBean,dayBean.day);
                }
            });
        }else {
            textView1.setText("暂无可使用补签卡，立即充值年卡会员");
            textView2.setText("可领取1张补签卡");
            pathBtn.setText("去充值");
            pathBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    patchDialog.dismiss();

                    startActivity(OpenVipSpendActivity.class);
                }
            });
        }

        cancelBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                patchDialog.dismiss();
            }
        });

        if(!patchDialog.isShowing()){
            patchDialog.show();
        }
    }

    private void showInviteDialog(DayBean dayBean,InviteBean inviteBean) {
        inviteDialog = new Dialog(this,R.style.Dialog_Translucent_Background);
        inviteDialog.setContentView(R.layout.invite_dialog);
        TextView titleText = inviteDialog.findViewById(R.id.invite_title_tv);
        titleText.setText(inviteBean.month + "月" + dayBean.day + "日 完成");
        TextView numText = inviteDialog.findViewById(R.id.invite_num_tv);
        numText.setText("成功邀请了" + dayBean.num + "个好友：");
        List<String> inviteUserList = dayBean.getInviteUserList();
        TextView textview1 = inviteDialog.findViewById(R.id.invite_mobile_tv1);
        TextView textview2 = inviteDialog.findViewById(R.id.invite_mobile_tv2);
        TextView textview3 = inviteDialog.findViewById(R.id.invite_mobile_tv3);
        TextView textview4 = inviteDialog.findViewById(R.id.invite_mobile_tv4);
        if(dayBean.num > 3){
            textview4.setVisibility(View.VISIBLE);
            textview1.setText(TMUitil.TMMobile(inviteUserList.get(0)));
            textview2.setText(TMUitil.TMMobile(inviteUserList.get(1)));
            textview3.setText(TMUitil.TMMobile(inviteUserList.get(2)));
        }else if(dayBean.num == 3){
            textview1.setText(TMUitil.TMMobile(inviteUserList.get(0)));
            textview2.setText(TMUitil.TMMobile(inviteUserList.get(1)));
            textview3.setText(TMUitil.TMMobile(inviteUserList.get(2)));
        }else if(dayBean.num >= 2){
            textview1.setText(TMUitil.TMMobile(inviteUserList.get(0)));
            textview2.setText(TMUitil.TMMobile(inviteUserList.get(1)));
            textview3.setVisibility(View.GONE);
        }else if(dayBean.num >= 1){
            textview1.setText(TMUitil.TMMobile(inviteUserList.get(0)));
            textview2.setVisibility(View.GONE);
            textview3.setVisibility(View.GONE);
        }

        inviteDialog.findViewById(R.id.invite_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                inviteDialog.dismiss();
            }
        });

        if(!inviteDialog.isShowing()){
            inviteDialog.show();
        }
    }

    private void patchCard(final InviteBean inviteBean,final PatchBean patchBean,final int day) {
        int userId = shuShanApplication.getCurrentUseId();
        UrlParse urlParse = new UrlCommParse(this, UrlConst.BASE_URL).appendRegion(UrlConst.POST_INVITE_PATCH);
        urlParse.putValue("user_id", userId)
                .putValue("year", inviteBean.year)
                .putValue("month", inviteBean.month)
                .putValue("day", day)
                .putValue("patch_id", patchBean.id);

        showWaitDialog();

        NetHelper.create()
                .url(urlParse.toStringOnlyHeader())
                .param(urlParse.toStringOnlyParam())
                .request(RequestType.REQUEST_TYPE_POST, new NetStrCommListener() {
                    @Override
                    protected void onCommon() {
                        dismissWaitDialog();
                    }

                    @Override
                    protected void onSuccess(String data) {
                        showPathSuccessDialog(inviteBean,day,patchBean);

                        UmengEventUtil.onEvent(shuShanApplication,"patch_card_success_id");
                    }

                    @Override
                    protected void onError(CallbackCode errorCode, NetRetBean netRetBean) {
                        showNetError(netRetBean);
                    }
                });
    }

    private void getInvite(final boolean isUpdat,final String year,final String month) {
        int userId = shuShanApplication.getCurrentUseId();
        UrlParse urlParse = new UrlCommParse(this, UrlConst.BASE_URL).appendRegion(UrlConst.GET_INVITE_FRIEND);
        urlParse.putValue("user_id", userId)
                .putValue("year", year)
                .putValue("month", month);

        showWaitDialog();

        NetHelper.create()
                .url(urlParse.toStringOnlyHeader())
                .param(urlParse.toStringOnlyParam())
                .request(RequestType.REQUEST_TYPE_POST, new NetSingleCommListener<InviteBean>() {
                    @Override
                    protected void onCommon() {
                        dismissWaitDialog();
                    }

                    @Override
                    protected void onSuccess(InviteBean inviteBean) {
                        gInviteBean = inviteBean;

                        totalText.setText(inviteBean.all_num + "");
                        patchText.setText(inviteBean.lack_id + "");
                        if(isUpdat){
                            if(inviteBean.getNum(currentDay) > 0){
                                taskText.setText("今日已完成");
                                taskImg.setImageResource(R.drawable.invite_smile);
                            }else {
                                taskText.setText("今日未完成");
                                taskImg.setImageResource(R.drawable.invite_cry);
                            }
                        }

                        setLayout(inviteBean);

                    }

                    @Override
                    protected void onError(CallbackCode errorCode, NetRetBean netRetBean) {
                        showNetError(netRetBean);
                    }
                });
    }

    private void setLayout(final InviteBean inviteBean) {
        if(inviteBean == null){
            return;
        }

        if(inviteBean.startYear == 0 || inviteBean.startMonth == 0 || inviteBean.startDay == 0){
            return;
        }


        String startStr = StringTools.toDateStr(inviteBean.startYear) +
                StringTools.toDateStr(inviteBean.startMonth) + StringTools.toDateStr(inviteBean.startDay);
        String nowStr = StringTools.toDateStr(nowYear) + StringTools.toDateStr(nowMonth) + StringTools.toDateStr(this.currentDay);
        Log.i(TAG,"startStr=" + startStr + " nowStr=" + nowStr);

        for (int i = 1;i <= sumOfSolarMonth;i++){
            String currentStr = StringTools.toDateStr(currentYear) + StringTools.toDateStr(currentMonth) + StringTools.toDateStr(i);
            if((Integer.parseInt(currentStr) < Integer.parseInt(startStr))
                    || (Integer.parseInt(currentStr) >= Integer.parseInt(nowStr))){
                continue;
            }

            final DayBean dayBean = inviteBean.getDayBean(i);
            if(dayBean != null){
                LinearLayout layout1 = findViewById(200+i+firstWeekDay);
                TextView tv = findViewById(i+firstWeekDay);
                TextView tv2 = findViewById(100+i+firstWeekDay);

                if(dayBean.is_patch == 1){
                    layout1.setBackgroundResource(R.drawable.invite_blue_shape);
                    tv.setTextColor(Color.WHITE);
                    tv2.setTextColor(Color.WHITE);
                    tv2.setVisibility(View.VISIBLE);
                    tv2.setText("已补签");
                }else if(dayBean.num > 0){
                    layout1.setBackgroundResource(R.drawable.invite_blue_shape);
                    tv.setTextColor(Color.WHITE);
                    tv2.setTextColor(Color.WHITE);
                    tv2.setVisibility(View.VISIBLE);
                    tv2.setText(dayBean.num + "个");

                    layout1.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            showInviteDialog(dayBean,inviteBean);
                        }
                    });
                }else {
                    layout1.setBackgroundResource(R.drawable.invite_white_shape);
                    tv2.setVisibility(View.VISIBLE);
                    tv2.setTextColor(Color.parseColor("#FF2323"));
                    tv2.setText("补签");

                    layout1.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            showPathDialog(dayBean,inviteBean);
                        }
                    });
                }
            }

        }
    }
}
